package com.cardvalue.sys.mode;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.cardvalue.sys.activity.HomeActivity;
import com.cardvalue.sys.activity.LoginActivity;
import com.cardvalue.sys.cache.LocalCache;
import com.cardvalue.sys.entity.Login;
import com.cardvalue.sys.entity.PostCreateAuth;
import com.cardvalue.sys.entity.User;
import com.cardvalue.sys.newnetwork.Config;

import com.cardvalue.sys.tool.LocationUtil;
import com.cardvalue.sys.tool.MD5Util;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.Date;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 与登录相关的接口
 * Created by cardvalue on 2016/4/13.
 */
public class LoginService {
    private   Retrofit retrofit;
    public ProgressDialog dialog;
    private Service.LoginService service;//登录
    private  UserService  userService;//获取用户
    private Service.CreateAuthorization CreateAuthService;//创建授权
    private Service.UpdatePassword   updatePwdService;//修改密码
    private Context context;
    public LoginService(Context context){
        this.context=context;
        retrofit = new Retrofit.Builder()
                .baseUrl(Config.getServerIp())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        dialog=new ProgressDialog(context);
        userService=new UserService(context);
    }

    /**
     * 登录接口
     * @param mobile
     * @param pass
     */
    public  void Login(String mobile, String pass, String pushId,final LoginCallback callback){
        service = retrofit.create(Service.LoginService.class);
        Call<Login> repos = service.attemptLogin(mobile,pass);
        repos.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {
                Login login=response.body();
                String error=login.getError()+"";

                if(!error.equals("null")){
                    MessageBox.ToastShow(login.getError()+"",context);
                    return;
                }
                if (callback != null) {
                    LocalCache.saveDataToLocal(context,"objectId",login.getObjectId());
                    LocalCache.saveDataToLocal(context,"accessToken",login.getAccessToken());
                    LocalCache.getStringLocalData(context,"objectId");
                    LocalCache.getStringLocalData(context,"accessToken");
                    Utiltools.printE("==LocalCache=Id==",LocalCache.getStringLocalData(context,"objectId"));
                    Utiltools.printE("==LocalCache=accessToken=",LocalCache.getStringLocalData(context,"accessToken"));
                    callback.cancelDialog();
                    callback.success();
                }

            /*    userService.getGetUserInfo(LocalCache.getStringLocalData(context, "objectId"), new UserService.UsesrCallback() {
                    @Override
                    public void success(User user) {
                      context.startActivity(new Intent(context,HomeActivity.class));
                    }

                    @Override
                    public void fail(String msg) {

                    }

                    @Override
                    public void cancelDialog() {

                    }
                });
*/
            }
            @Override
            public void onFailure(Call<Login> call, Throwable t) {

            }
        });
    }


    public  interface  LoginCallback {
        void success();

        void fail(String msg);

        void cancelDialog();
    }

    /**
     * 创建授权
     * @param mobile  //手机号码
     *  @param  pass//加密后的密码
     * @param isLogin  //判断传入进来的isLogin值，如果是isLogin的话，就是下面要登录的操作，
     *                 负责，注册
     * @throws Exception
     */
    public void attemptCreateAuthorization(final String mobile, final String pass, String ip, final String pushId, final String isLogin,final LoginCallback callback) throws Exception{
        CreateAuthService=retrofit.create(Service.CreateAuthorization.class);
        PostCreateAuth postCreateAuth=new PostCreateAuth();
        WebView webview = new WebView(context);
        webview.layout(0, 0, 0, 0);
        WebSettings settings = webview.getSettings();
        String ua = settings.getUserAgentString();
        Map<String,String> map= LocationUtil.getMap();
        postCreateAuth.setMobilePhone(mobile);//手机号码
        postCreateAuth.setAgent(ua);//浏览器的User-Agent (UA) 字符串
        postCreateAuth.setDeviceNumber(map.get("imel")==null?"":map.get("imel").toString());//设备号
        postCreateAuth.setGps(map.get("ongitude")+","+map.get("atitude"));//经纬度
        postCreateAuth.setType(5);//5：同意注册条款、申请条款、确认放款条款和征信报告协议
        postCreateAuth.setIp(ip);//
        postCreateAuth.setTime(new Date().toLocaleString());
        Call<PostCreateAuth> call = CreateAuthService.attemptCreateAuthorization(postCreateAuth);
        call.enqueue(new Callback<PostCreateAuth>() {
            @Override
            public void onResponse(Call<PostCreateAuth> call, Response<PostCreateAuth> response) {
                PostCreateAuth CreateAuth=response.body();
                String error=CreateAuth.getError()+"";
                if(!error.equals("")){
                    MessageBox.ToastShow(CreateAuth.getError()+"",context);
                    return;
                }
                Log.e("创建授权===objectId",CreateAuth.getObjectid()+"");
                Log.e("创建授权2===objectId",CreateAuth.getCreatedAt()+"");
                if(isLogin.equals("isLogin")){//登录之前没有授权，所以授权之后登录
                    MessageBox.show(dialog,"登录中","登录中...");
                    Login(mobile,pass,pushId, null);
                }
            }

            @Override
            public void onFailure(Call<PostCreateAuth> call, Throwable t) {

            }
        });
    }

    /**
     * 修改密码
     * @param oldpwd  //旧密码
     * @param newpwd  //新密码
     * @param // objectId 登录成功返回的
     */
    public void updatePwdService(String oldpwd,String newpwd){
        updatePwdService=retrofit.create(Service.UpdatePassword.class);
        Login login=new Login();
        login.setOldPassword(oldpwd);
        login.setNewPassword(newpwd);
        Call<Login> repos = updatePwdService.attempUpdatePassword(
                LocalCache.getStringLocalData(context,"objectId"),
                LocalCache.getStringLocalData(context,"accessToken"),
                LocalCache.getStringLocalData(context,"objectId"),login);
        Utiltools.printE("==呵呵=","呵呵"+MD5Util.MD5(oldpwd)+"呵呵"+MD5Util.MD5(newpwd)+"呵呵");
        repos.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {
                Login  updataPaw=response.body();
                Utiltools.printE("=code==","----"+updataPaw.getCode()+"");
                Utiltools.printE("==erro=","----"+updataPaw.getError()+"");
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {

            }
        });

    }





}
